<?php

!defined('DEBUG') AND exit('Access Denied.');

$action = param(1);

if(!admin_authority_check()) header("Location:".url('index-login'));
if(empty($action) || $action == 'list') {
	//参数
	$parent   = param('parent');
	$srchtype = param(2);
	$keyword  = urldecode(param(3));
	$export = param('export', 0);	// 导出excel
	//条件
	if($parent){
		$header['title'] = $parent."的会员列表";
		$parent_info = user_read_by_username($parent);
		if(!empty($parent_info)){//代理存在
			$condition = array('parent'=>$parent_info['uid']);
		}else{//代理不存在
			$condition = array('parent'=>-1);
		}
	}else{
		$header['title'] = "会员列表";
		$condition = !$srchtype || !$keyword ? array() : array($srchtype=>array('like'=>'%'.$keyword.'%'));
	}
	//导出excel
	if($export){
		$log = db_find('user', $condition, array('uid'=>'-1'), 1, 10000);
		if(!empty($log)){
			//colname
			$colname = array('用户名','商户号','用户组','上级代理','费率','余额','累计流水','累计提款','银行开关','注册时间','登录时间','注册IP','登录IP','邮箱','真实姓名','身份证号','手机号','QQ号','网站','IP白名单','银行');
			//data
			$data = array();
			foreach($log as $k=>$v){
				$data[$k]['username'] = ' '.$v['username'];//用户名
				$data[$k]['apino'] = ' '.$v['apino'];//商户号
				//用户组
				if($v['is_proxy']==1) $data[$k]['type'] = '代理';
				elseif($v['is_admin']==1) $data[$k]['type'] = '管理员';
				elseif($v['is_open']==0) $data[$k]['type'] = '待审核';
				else $data[$k]['type'] = '商户';
				//上级代理
				$data[$k]['proxy'] = '';
				if($v['parent']){
					$_proxy = user_read($v['parent']);
					$data[$k]['proxy'] = ' '.$_proxy['username'];
				}				
				//
				$data[$k]['rate'] = $v['rate'];//费率
				$data[$k]['coin'] = $v['coin'];//余额
				$data[$k]['tj_pay'] = $v['tj_pay'];//累计流水
				$data[$k]['tj_cash'] = $v['tj_cash'];//累计提款
				$data[$k]['bank_open'] = ($v['bank_open']==1?'开':'关');//银行开关
				$data[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);//注册时间
				$data[$k]['login_time'] = date('Y-m-d H:i:s', $v['login_time']);//登录时间
				$data[$k]['create_ip'] = $v['create_ip'];//注册IP
				$data[$k]['login_ip'] = $v['login_ip'];//登录IP
				$data[$k]['email'] = $v['email'];//邮箱
				$data[$k]['info_name'] = $v['info_name'];//真实姓名
				$data[$k]['info_id'] = ' '.$v['info_id'];//身份证号
				$data[$k]['info_mobile'] = ' '.$v['info_mobile'];//手机号
				$data[$k]['info_qq'] = ' '.$v['info_qq'];//QQ号
				$data[$k]['info_site'] = $v['info_sitename'].$v['info_sitelink'];//网站
				$data[$k]['allow_ips'] = $v['allow_ips'];//IP白名单
				//银行
				$data[$k]['bank'] = '';
				$bank = db_find('user_bank', array('uid'=>$v['uid']));
				if(!empty($bank)){
					foreach($bank as $b){
						$data[$k]['bank'].= $b['bank'].'(卡号：'.$b['code'].' 持卡人：'.$b['name'].') ';
					}
				}
			}
			//
			$name = '会员列表';
			if($parent!=''){
				$name=$parent.'的会员列表';
			}
			$title = $name;
			$filename = $name;
			export_excel($title,$colname,$data,$filename);//下载excel
		}else{
			exit('没有数据');
		}
	}
	//统计
	$total = db_find_one('user', $condition, array(), array('sum(coin) as coin_total,sum(tj_pay) as tj_pay_total'));
	//
	$page     = param(4, 1);
	$pagesize = 20;
	$users = db_find('user', $condition, array('uid'=>'-1'), $page, $pagesize);
	$url_export= url("user-list-$srchtype-".$keyword)."?parent=$parent&export=1";
	$pagination = pagination(url("user-list-$srchtype-".$keyword.'-{page}')."?parent=$parent", db_count('user', $condition), $page, $pagesize);
	include _include(ADMIN_PATH."view/htm/user_list.htm");

} elseif($action == 'update') {

	$_uid = param(2, 0);
	if($method == 'GET') {
		$header['title'] = "用户编辑";
		$header['mobile_title'] = "用户编辑";
		$_user = user_read($_uid);
		$bank = db_find('user_bank', array('uid'=>$_uid));
		if($_user['is_admin']==0 && $_user['is_proxy']==0){
		    $daili = db_find('user',array('is_proxy'=>1));
        }
		include _include(ADMIN_PATH."view/htm/user_update.htm");

	} elseif($method == 'POST') {
		$_user = user__read($_uid);
		$group = param('group');
		$array = array();
		if($group==1){
			$array['is_admin'] = 0;
			$array['is_proxy'] = 1;
			$array['is_open'] = 1;
		} else if($group==2) {
			$array['is_admin'] = 1;
			$array['is_proxy'] = 0;
			$array['is_open'] = 1;
		} else if($group==3){
			$array['is_proxy'] = 0;
			$array['is_admin'] = 0;
			$array['is_open'] = 0;
		}else {
			$array['is_proxy'] = 0;
			$array['is_admin'] = 0;
			$array['is_open'] = 1;
		}
		if($array['is_admin']==0 && $array['is_proxy']==0){
		    $array['parent'] = param('parent');
        }
		$array['email'] = param('email');
		$array['username'] = param('username');
		$array['password'] = param('password') ? md5(md5(param('password')).$_user['salt']) : $_user['password'];
		$array['password_ti'] = param('password_ti') ? md5(md5(param('password_ti')).$_user['salt']) : $_user['password_ti'];
		//$array['coin'] = param('coin');
		$array['info_name'] = param('name');
		$array['info_id'] = param('id');
		$array['info_mobile'] = param('mobile');
		$array['info_qq'] = param('qq');
		$array['info_sitename'] = param('sitename');
		$array['info_sitelink'] = param('sitelink');
		$array['allow_ips'] = param('allow_ips');
		$array['bank_open'] = param('bank_open');
		$r = user__update($_uid, $array);
		$bankname = param('bankname', array());
		$bankcode = param('bankcode', array());
		$bankhost = param('bankhost', array());
		foreach($bankname as $k=>$n){
			if($n=='' || $bankcode[$k]=='' || $bankhost[$k]==''){
				db_delete('user_bank', array('id'=>$k));
			}else{
				db_update('user_bank', array('id'=>$k), array('bank'=>$n,'code'=>$bankcode[$k],'name'=>$bankhost[$k]));
			}
		}
		$r === FALSE AND message(-1, "编辑失败");
		message(0, "编辑成功");
	}

} elseif($action == 'add') {
	if($method == 'GET') {
		$header['title'] = "用户添加";
		$header['mobile_title'] = "用户添加";
		include _include(ADMIN_PATH."view/htm/user_add.htm");

	} elseif($method == 'POST') {
		$group = param('group');
		$array = array();
		if($group==1){
			$array['is_admin'] = 0;
			$array['is_proxy'] = 1;
			$array['is_open'] = 1;
		} else if($group==2) {
			$array['is_admin'] = 1;
			$array['is_proxy'] = 0;
			$array['is_open'] = 1;
		} else if($group==3){
			$array['is_proxy'] = 0;
			$array['is_admin'] = 0;
			$array['is_open'] = 1;
		}else {
			$array['is_proxy'] = 0;
			$array['is_admin'] = 0;
			$array['is_open'] = 0;
		}
		$array['rate'] = param('rate');
		$array['salt'] = rand(1000, 9999);
		$array['email'] = param('email');
		$array['username'] = param('username');
		$array['password'] = md5(md5(param('password')).$array['salt']);
		$array['password_ti'] = md5(md5(param('password_ti')).$array['salt']);
		//$array['coin'] = param('coin');
		$array['info_name'] = param('name');
		$array['info_id'] = param('id');
		$array['info_mobile'] = param('mobile');
		$array['info_qq'] = param('qq');
		$array['apino'] =mt_rand(100000,999999);
		$array['apisecret'] =md5(time().mt_rand());
		$array['info_sitename'] = param('sitename');
		$array['info_sitelink'] = param('sitelink');
		$array['allow_ips'] = param('allow_ips');
		$array['bank_open'] = param('bank_open');
		$array['create_time'] = $time;
		$r = db_insert('user', $array);
        db_sql_find_one('SET AUTOCOMMIT=0');
//        try{
        $cate = db_sql_find("SELECT * FROM ".$db->tablepre."cate where is_public=1 and status=1");//所有的公共店铺
        foreach ($cate as $key=>$value){
            $arr = array('uid'=>$r,'name'=>$value['name'],'is_public'=>2,'status'=>1);
            $cate_id = db_insert('cate',$arr);//新用户的复制店铺id
            $price = db_sql_find("SELECT * FROM ".$db->tablepre."cate_price where cid=".$value['id']." and status=1");//查询所有的价格段
            foreach ($price as $k=>$v){
                $arr = array('cid'=>$cate_id,'price_start'=>$v['price_start'],'price_end'=>$v['price_end'],'status'=>1);
                $price_id = db_insert('cate_price',$arr);//新用户的复制价格段id
                $goods = db_sql_find("SELECT * FROM ".$db->tablepre."cate_goods where cid=".$value['id']." and pid=".$v['id']." and status=1");
                foreach ($goods as $ke=>$va){
                    $arr = array('cid'=>$cate_id,'pid'=>$price_id,'name'=>$va['name'],'status'=>1);
                    db_insert('cate_goods',$arr);
                }
            }
        }
//        }catch (Exception $e){
//            return array(1,'注册成功！请耐心等待审核通过。添加默认模板失效');
//        }
        db_sql_find_one('COMMIT');
		$r === FALSE AND message(-1, "添加失败");
		message(0, "添加成功");
	}

} elseif ($action == 'delete') { 

	if($method != 'POST') message(-1, 'Method Error.');
	$_uid = param('uid', 0);
	$r = user__delete($_uid);
	$r === FALSE AND message(-1, lang('delete_failed'));
	db_delete('finance_power', array('uid'=>$_uid));//删除权限
	message(0, "删除成功");

} elseif($action == 'rate') {

	$_uid = param(2);
	$_user = user_read($_uid);
	$_user_parent = array();
	if($_user['parent']){
		$_user_parent = user_read($_user['parent']);
	}
	if($method == 'GET') {
		$rate_note='';
		if(!empty($_user_parent)) $rate_note='费率不能低于其代理的费率('.$_user_parent['rate'].')';
		$header['title'] = "用户费率修改";
		$header['mobile_title'] = "用户费率修改";
		include _include(ADMIN_PATH."view/htm/user_rate.htm");
	} elseif($method == 'POST') {
		$rate = param('rate');
		if(!empty($_user_parent) && $rate<$_user_parent['rate']) message(0, "费率不能低于其代理的费率");
		$r = user__update($_uid, array('rate'=>$rate));
		$r === FALSE AND message(-1, "更改失败");
		message(1, "更改成功");
	}

} elseif($action == 'finance') {
	//参数
	$srchtype = param(2);
	$keyword  = urldecode(param(3));
	$page     = param(4, 1);
	$pagesize = 20;
	//条件
	$condition = !$srchtype || !$keyword ? array() : array($srchtype=>array('like'=>'%'.$keyword.'%'));
	//查询
	$header['title'] = "财务列表";
	$users = db_find('finance', $condition, array('uid'=>'-1'), $page, $pagesize);
	$pagination = pagination(url("user-finance-$srchtype-".$keyword.'-{page}'), db_count('finance', $condition), $page, $pagesize);
	include _include(ADMIN_PATH."view/htm/finance.htm");

} elseif($action == 'financeadd') {

	if($method == 'GET') {
		$header['title'] = "财务添加";
		$header['mobile_title'] = "财务添加";
		$proxy = db_sql_find("SELECT uid,username FROM ".$db->tablepre."user where is_proxy=1 order by uid asc");
		$merchant = db_sql_find("SELECT uid,username FROM ".$db->tablepre."user where is_proxy<>1 and is_admin<>1 order by uid asc");
		include _include(ADMIN_PATH."view/htm/finance_add.htm");

	} elseif($method == 'POST') {
		$array = array();
		$array['salt'] = rand(1000, 9999);
		$array['username'] = param('username');
		$array['password'] = md5(md5(param('password')).$array['salt']);
		$array['allow_ips'] = param('allow_ips');
		$array['create_time'] = $time;
		$array['create_ip'] = $ip;
		$r = db_insert('finance', $array);
		$r === FALSE AND message(-1, "添加失败");
		//权限
		$power = _POST('power');
		if(!empty($power)){//有选权限
			foreach($power as $p){
				db_insert('finance_power', array('fid'=>$r, 'uid'=>$p));//插入权限
			}
		}
		//
		message(0, "添加成功");
	}

} elseif($action == 'financeupdate') {

	$_uid = param(2, 0);
	$_user = db_find_one('finance', array('uid'=>$_uid));
	if($method == 'GET') {
		$header['title'] = "财务编辑";
		$header['mobile_title'] = "财务编辑";
		$proxy = db_sql_find("SELECT uid,username FROM ".$db->tablepre."user where is_proxy=1 order by uid asc");
		$merchant = db_sql_find("SELECT uid,username FROM ".$db->tablepre."user where is_proxy<>1 and is_admin<>1 order by uid asc");
		$power_old_arr = db_sql_find("SELECT uid FROM ".$db->tablepre."finance_power where fid=$_uid");
		$power_old = array();
		if(!empty($power_old_arr)){
			foreach($power_old_arr as $po){
				$power_old[] = $po['uid'];
			}
		}
		include _include(ADMIN_PATH."view/htm/finance_update.htm");

	} elseif($method == 'POST') {
		$array = array();
		$array['username'] = param('username');
		$array['password'] = param('password') ? md5(md5(param('password')).$_user['salt']) : $_user['password'];
		$array['allow_ips'] = param('allow_ips');
		$r = db_update('finance', array('uid'=>$_uid), $array);
		$r === FALSE AND message(-1, "编辑失败");
		//权限
		$power = _POST('power');
		db_delete('finance_power', array('fid'=>$_uid));//删除原权限
		if(!empty($power)){//有选权限
			foreach($power as $p){
				db_insert('finance_power', array('fid'=>$_uid, 'uid'=>$p));//插入权限
			}
		}
		//
		message(0, "编辑成功");
	}

} elseif ($action == 'financedel') { 

	if($method != 'POST') message(-1, 'Method Error.');
	$_uid = param('uid', 0);
	$r = db_delete('finance', array('uid'=>$_uid));//删除财务
	$r === FALSE AND message(-1, lang('delete_failed'));
	db_delete('finance_power', array('fid'=>$_uid));//删除权限
	@unlink('../tmp/remind-cash-'.$_uid.'.txt');//删除提现提醒
	message(0, "删除成功");

}


function checkSms($code,$uid){
    $arr = db_find_one('smscode',array('uid'=>$uid,'smscode'=>$code));
    if(empty($arr)){
        return false;
    }elseif ($arr['status']==1){
        return false;
    }else{
        $now = strtotime(date('Y-m-d H:i:s'));
        if (($arr['time']+90)<$now) {
            return false;
        }else{
            return true;
        }

    }
}

function randNum(){
    $num = rand(1000,9999);
    return $num;
}
?>